package com.casic.worklog.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author eollse-wj
 * @ClassName JwtUtil
 * @date 2020/6/10
 * @description
 */
public class JwtUtil {
    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "BE5CDC2639677B0786D404432D476192";

    /**
     * 生成签名
     * @param username
     * @param userId
     * @return
     */
    public static String sign(String username, String userId, long expireTime){
        //过期时间
        Date date = new Date(System.currentTimeMillis() + expireTime);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username, userId信息，生成签名
        return JWT.create()
                .withHeader(header)
                .withClaim("loginName", username)
                .withClaim("userId", userId)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            e.toString();
            return false;
        }
    }
}
